// pages/my/exam/exam.js
const { httpPost, httpGet } = require('../../common/js/http')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    idx: 0,//题目下标
    num: 0,//分数
    minute: '',
    second: '',
    userAnswer: {}, //用户选择的答案
    answerList:[{}], //记录用户所有题的答案 用于做判断
    total: 10,
    isAnswerAll: false
    // nowNum: 5
  },

  jumpBackTitle(e){
    let that = this
    let idx = that.data.idx//第几题
    // console.log("k",idx)
    this.setData({
      idx: idx - 1
    })
  },
  jumpNavTitle(e){
    let that = this
    let idx = that.data.idx
    let arr = this.data.answerList[idx].list //当前题目所有选项
    let titleScore = this.data.answerList[idx].titleScore
    let answerArr = arr.filter(item => {
      return item.score != ''
    })
    let answerTitleScore = 0
    arr.forEach(item => {
      if(item.score != ''){
        answerTitleScore += Number(item.score)
      }
    })
    if(answerArr.length == 0){
      wx.showToast({
        icon: 'none',
        title: '请先赋分',
      })
    }else if(answerTitleScore != titleScore){
      wx.showToast({
        icon: 'none',
        title: '请注意分值',
      })
    }else{
      httpPost({
        url: "/app/orderExam/admin/updateOrderTitleOptionFF",
        data: {
          orderExamId: this.data.list[idx].orderExamId,
          titleId: this.data.list[idx].titleId,
          fuFenOptionsList: answerArr
        },
        isLoding: true,
        lodingMsg: '加载中...'
      }).then(res => {
        if(res.errorCode == 0 && res.data != 0){
          if(idx+1 == this.data.total){
            //答题完毕
            this.submit(this.data.list[idx].orderExamId)
          }else{
            // setTimeout(() =>{
              this.setData({
                idx: idx + 1
              })
            // },2000)
          }
        }else{
          wx.showToast({
            icon: 'none',
            title: res.message || '异常',
          })
        }
      })
    }
  },
  selectTitle(e){
    let userAnswerData = e.currentTarget.dataset
    let arr = this.data.answerList
    let idx = this.data.idx
    arr[this.data.idx].answer = userAnswerData.index+''
    this.setData({
      userAnswer: userAnswerData,
      answerList: arr
    })
    if(userAnswerData.hasOwnProperty('titleid')){
      httpPost({
        url: "/app/orderExam/admin/updateOrderTitleOption",
        data: {
          orderExamId: userAnswerData.orderexamid,
          titleId: userAnswerData.titleid,
          optionsId: userAnswerData.optionsid
        },
        isLoding: true,
        lodingMsg: '加载中...',
        contentType: {"Content-Type": "application/x-www-form-urlencoded" }
      }).then(res => {
        if(res.errorCode == 0 && res.data == 1){
          if(idx+1 == this.data.total){
            //答题完毕
            // this.submit(userAnswerData.orderexamid)
            this.setData({
              isAnswerAll: true
            })
          }else{
            setTimeout(() => {
              this.setData({
                idx: idx + 1
              })
            },500)
          }
        }else{
          wx.showToast({
            icon: 'none',
            title: res.message || '异常',
          })
        }
      })
    }
  },
  onInput(e){
    let idx = this.data.idx
    let val = e.detail.value.trim()
    let index = e.currentTarget.dataset.index
    let arr = this.data.answerList
    arr[idx].list.forEach((item,i) => {
      if(i == index){
        item.score = val
      }
    })
    this.setData({
      answerList: arr
    })
  },
  submit(orderExamId){
    httpPost({
      url: "/app/orderExam/admin/submitOrderExam",
      data: {
        orderExamId
      },
      isLoding: true,
      lodingMsg: '加载中...',
      contentType: {"Content-Type": "application/x-www-form-urlencoded" }
    }).then(res => {
      if(res.errorCode == 0){
        wx.redirectTo({
          url: '../examResult/examResult?orderExamId=' + orderExamId + '&examType=' + this.data.examType,
        })
      }else{
        wx.showToast({
          icon: 'none',
          title: res.message || '异常',
        })
      }
    })
  },
  submitExam(){
    let data = this.data.list[this.data.idx]
    if(data.titleType == 2){
      //赋分类型
      this.jumpNavTitle()
    }else{
      // let arr = this.data.answerList
      // if(arr[this.data.idx].answer != ''){
        this.submit(data.orderExamId)
      // }else{
      //   wx.showToast({
      //     icon: 'none',
      //     title: '请先答完所有题目111',
      //   })
      // }
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    httpGet({
      url: "/app/orderExam/admin/getOrderExamDetail",
      data: {orderExamId: options.orderExamId,isNeedTitles: 1},
      isLoding: true,
      lodingMsg: '加载中...'
    }).then(res => {
      // console.log(res)
      if(res.errorCode == 0){
        wx.setNavigationBarTitle({
          title: res.data.examName
        })
        let length = res.data.orderCateTitleVoList.length
        let arr = []
        res.data.orderCateTitleVoList.forEach((item,index) =>{
          if(item.titleType == 2 ){
            let arrInitialization = []
            item.titleOptionsList.forEach((list,i) => {
              arrInitialization.push({optionId: list.id,score: ''})
            })
            arr.push({list: arrInitialization,titleScore: item.titleScore})
          }else{
            
            arr.push({answer: ''})
          }
          if(item.optionsId){
            if(length == index+1){
              this.setData({
                idx: index,
                isAnswerAll: true
              })
            }else{
              this.setData({
                idx: index+1
              })
            }
          }
        })
        let typeEnd = res.data.orderCateTitleVoList[res.data.orderCateTitleVoList.length-1].titleType
        // console.log('type',typeEnd)
        if(typeEnd == '2'){
          this.setData({
            isAnswerAll: true
          })
        }
        this.setData({
          list: res.data.orderCateTitleVoList,
          answerList: arr,
          total: res.data.orderCateTitleVoList.length,
          examType: res.data.examType
        })
        this.timeDown(res.data.examAnswerTime*60 - res.data.examAnsweredTime)
      }
    })
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },
  timeDown(time){
    if(time <= 0){
      this.setData({
        minute: '00',
        second: '00'
      })
      return
    }
    // let  time = 1800;//30分钟换算成1800秒
    let timer = setInterval(() => {
        time = time - 1;
        let minute = parseInt(time/60) < 10 ? '0' + parseInt(time/60) :parseInt(time/60)
        let second = parseInt(time%60) < 10 ? '0' + parseInt(time%60) :parseInt(time%60)
        this.setData({
          minute,
          second
        })
        if(minute == 0 && second == 0){
          clearInterval(timer)
        }
    },1000)
  }
})
